// 单列模式，包含简单模式以及复杂模式两种展示类型

import { useQuasar } from '@teld/q-components';
// import {
//   TChip,
//   TInfiniteScroll,
//   TInnerLoading,
//   TItem,
//   TItemSection,
//   TList,
// } from 't';
import TChip from 't/basic/chip';
import TInfiniteScroll from 't/basic/infinite-scroll';
import TInnerLoading from 't/basic/inner-loading';
import TItem from 't/basic/item';
import TItemSection from 't/basic/item-section';
import TList from 't/basic/list';
import TTable from 't/basic/table';
import TTr from 't/basic/table/Tr';
import TTh from 't/basic/table/Th';
import TTd from 't/basic/table/Td';
import TCheckbox from 't/basic/checkbox';
import TInput from '../../basic/input';
import NoDataImage from 'src/assets/no-data.png';
import {
  computed,
  defineComponent,
  inject,
  onMounted,
  ref,
  toRefs,
  watch,
} from 'vue';
export default defineComponent({
  name: 'SelectHelperSingleRow',
  components: {
    TChip,
    TInfiniteScroll,
    TItem,
    TList,
    TItemSection,
    TInnerLoading,
    TTable,
    TTr,
    TTh,
    TTd,
    TCheckbox,
    TInput
  },
  props: {
    width: String,
    simple: {
      type: Boolean,
      default: true,
    },
    multiple: Boolean,
    position: String,
    columns: {
      type: Array,
    },
    valueField: String,
    labelField: String,
    helperCode: String,
    placeholder: String,
    type: String,
    checkList: Array,
    filter: String,
    subsidiary: String,
    countPerPage: [String, Number],
    pagination: Boolean,
    targetSelection: Array,
    targetSelectList: Array,
    iconEnable: Boolean,
    iconDataSource: String,
    height:[String,Number],
    isMultiseriate:Boolean,
    columnNumber:Number,
    dropPosition:String,
    columnarPattern:Boolean
  },
  emits: ['updateSelectList','update:filter','close'],

  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const {
      width,
      multiple,
      position,
      checkList,
      columns,
      valueField,
      labelField,
      helperCode,
      placeholder,
      type,
      filter,
      subsidiary,
      simple,
      countPerPage,
      pagination,
      targetSelection,
      targetSelectList,
      iconEnable,
      iconDataSource,
      height,
      isMultiseriate,
      columnNumber,
      dropPosition,
      columnarPattern
    } = toRefs(props);
    onMounted(() => {});
    function onClickHandler(params) {}
    const itemsMenu = ref([]);
    const visible = ref(false);
    const $q = useQuasar();
    const test = ref('')
    // const columns = [
    //   {
    //     name: 'name',
    //     required: true,
    //     label: 'Dessert (100g serving)',
    //     align: 'left',
    //     field: row => row[valueField.value],
    //     format: val => `${val}`,
    //     sortable: true,
    //   },
    // ];
 const columnsByComputed = computed(() => {
   return columns.value
     .map(item => {
       if (item.isShow) {
         return {
           name: item.dataField,
           required: true,
           label: item.caption,
           align: item.textAlign ? item.textAlign : 'left',
           field: item.dataField,
           width: item.width ? item.width : '',
          //  sortable: true,
          //  sort: (a, b) => a > b,
         };
       }
     })
     .filter(
       item =>
         item &&
         ((simple.value && item.dataField == labelField.value) ||
           !simple.value),
     );
 });
    const rows = ref([]);
    const selection = ref(targetSelection.value ? _.cloneDeep(targetSelection.value):[]);
    watch(() => targetSelection.value, () => {
      selection.value =  _.cloneDeep(targetSelection.value) ;
    })
    const getDateByFilter = () => {
      return rows.value;
    }
    expose({ rows,getDateByFilter });
    const searchByFilter = inject('searchByFilter');
    let page = 0;
    let isloading = false
    const onLoadMenu = (index, done,clearRows) => {
       if(isloading||(columnarPattern.value&&multiple.value)) return done()
      isloading=true
      let _rows = pagination.value ? countPerPage.value : null;
      if (!_rows) {
        rows.value = [];
      }
      if (type.value == 'byPreview') {
        rows.value = checkList.value;
        return;
      }
      if (type.value == 'filter' && !filter.value) {
        return (rows.value = []);
      }
      
      visible.value = true;
      if (index > 1) {
        page++;

        searchByFilter(page, _rows  ||10, filter.value).then(res => {

          if (!rows.value || page == 1||res.Count==0||clearRows) {
            rows.value = [];
          }
          res.List ? (rows.value = rows.value.concat(res.List)) : '';
          
          if (res.List.length == _rows && rows.value.length < res.Count) {
             
             isloading=false
            if (rows.value.length < 20) {
             return  onLoadMenu(2,done)
            }
          }
          done();
        });
      } else {
        done();
      }
    };
    if(!(columnarPattern.value&&multiple.value)){   // 初次请求一次
      onLoadMenu(2,()=>{})
     }else{
      emit('loadData',rows)
    }
  
    const _pagination = ref({
      sortBy: 'desc',
      descending: false,
      page: 1,
      rowsPerPage: 10,
      rowsNumber: 1,
    });
    let query = null;
    const tableRef = ref(null);
    watch(
      () => filter.value,
      (o, n) => {
        if(o==n||(columnarPattern.value&&multiple.value)) return
        
        if (query) {
          window.clearTimeout(query);
          query = null;
        }
        query = window.setTimeout(() => {
          isloading=false
          // rows.value = [];
          page=0
          _pagination.value.page = 1;
          onLoadMenu(2, () => {},true);
        }, 200);
      },
    );
    const scrollTargetRef = ref(null);
    //已选择数据集合
    const selectList = ref(targetSelectList.value ? _.cloneDeep(targetSelectList.value) : []);
    watch(() => targetSelectList.value, () => {
      if (JSON.stringify(selectList.value) == JSON.stringify(targetSelectList.value)) {
        return
      }
      selectList.value = _.cloneDeep(targetSelectList.value) ;
    })
    //定义点击事件
    const trTargetClick = target => {
      if (type.value == 'byPreview') return;
      if (
        selectList.value.some(
          item => item[valueField.value] == target[valueField.value],
        )
      ) {
        selectList.value = selectList.value.filter(
          item => item[valueField.value] != target[valueField.value],
        );
      } else {
        if (!multiple.value) {
          selectList.value = [];
          emit('update:filter','')
        }
        selectList.value.push(target);
      }
    };
    const checkAll = computed(() => {
      if (
        rows.value.every(item =>
          selection.value.some(sel => item.name == sel),
        )
      ) {
        return ['ischecked'];
      } else if (
        !rows.value.some(item =>
          selection.value.some(sel => item.name == sel),
        )
      ) {
        return [];
      }
      return null;
    });

    if (multiple.value) {
      watch(
        () => selectList.value,
        () => {
          if (isMultiseriate.value) return;
          selection.value = selectList.value.map(item => item[valueField.value]);
          emit('updateSelectList', selectList.value);
        },
        {
          immediate:true,
          deep: true,
        },
      );
    }
    let isClicking = false;
    const hightLight = target => {
      if (!filter.value) return target;
      // <span style="background-color:#FFAA00;">${filter.value}</span>
      const hightStr = `<span style="color:var(--t-color);display:inline !important">${filter.value}</span>`;

      const strReg = new RegExp(filter.value, 'gi');

      return target.replace(strReg, hightStr);
    };
    function readerCheckBox(props) {
      let isChecked = selection.value.some(
        item => item == props.row[valueField.value],
      );
      return (
        <t-checkbox
          size='sm'
          onClick={() => {
            trTargetClick(props.row);
          }}
          v-model={isChecked}
        />
      );
    }

    const renderInfinite = () => {
      if(rows.value.length==0){
        return <div style={'height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;flex-wrap:wrap'}>
          <img style="display:inline-block;width:120px;height:120px" src={NoDataImage}  />
            <p style={'width:100%;text-align:center;margin-top:16px;color:rgba(0,0,0,.32)'}>无搜索结果</p>
        </div>
      }
      return (
        <t-infinite-scroll
             onLoad={pagination.value?onLoadMenu:()=>{}}
          offset={450}
          scroll-target={scrollTargetRef.value}
        >

          <t-table
            rows={rows.value}
            columns={columns.value}
            class={`select_helper_popup_single_row_table ${isMultiseriate.value?'isMultiseriate':''}`}
            row-key='name'
            selection='single'
            hide-header
            hide-bottom
            rows-per-page-options={[0]}
            ref={tableRef}
            v-model:pagination={_pagination.value}
            columns={columnsByComputed.value}
          >
            {{
              body: props => {
                // console.log(props)
                return (
                  
                  <t-tr
                    props={props}
                    onClick={() => {
                      if (!isClicking) {
                        trTargetClick(props.row);
                        isClicking = true;
                        window.setTimeout(() => {
                          isClicking = false;
                        }, 300);
                      } else {
                        // close();
                      }
                      if (!multiple.value&&!isMultiseriate.value) {
                        emit('updateSelectList', selectList.value);
                      }
                    }}
               
                    style={`width:calc(${100/(isMultiseriate.value?columnNumber.value?columnNumber.value:3:1)}% - 0px);${type.value == 'byPreview'||1?'display:flex':''}`}
                    class={`${ selectList.value.some(
                      item =>
                        item[valueField.value] == props.row[valueField.value],
                    )&&!multiple.value
                      ? 'select_helper_popup_table_tr_checked'
                      : ''} `
                     
                    }
                  >
                    {(() => {
                      let Template = [];
                      if (multiple.value&&!isMultiseriate.value) {
                        Template.push(
                          <t-td auto-width style={'flex: none;width: 34px;display: flex;align-items: center;'}>
                            {readerCheckBox(props)}
                          </t-td>,
                        );
                      }
                      for (let i in props.row) {
                        if (simple.value && i != labelField.value) {

                        } else {
                           Template.push(
                             <t-td key={i} props={props} style={`${type.value == 'byPreview'||1?'flex:1 1 auto':''}`}>
                               {/* 自定义内容区域 calc(100vw - 60px)*/}
                               <div
                                 style={
                                   'display: flex;justify-content: space-between;align-items: center;    max-width: calc(100vw - 0px);text-wrap: auto;line-height: 1.5 !important;min-height:36px'
                                 }
                               >
                                 <div style={
                                   'display: flex;justify-content: satrt;align-items: center;gap:8px;width:100%'
                                 }>
                                  
                                   <div style={`
                                        width: 100%;
                                        display: flex;
                                        justify-content: satrt;
                                        align-items: center;gap:8px
                                    `}>
                                     
                                      
                                     {iconEnable.value ? (() => {
                                         
                                         return  <span style={
                                            'display: flex;justify-content: satrt;align-items: center;'
                                          }>
                                          <img src={props.row[iconDataSource.value]}   style={($q.screen.xs||$q.platform.is.mobile)?'':'width:24px;height:24px;margin-left:8px;border-radius:2px'}/>
                                          </span>
                                        })() : ''}
                                      <div>
                                        <span
                                          class='select_helper_popup_single_row_table_mainKeyWord'
                                          style={
                                            subsidiary.value
                                              ? 'line-height:1.5'
                                              : 'font-weight:400;line-height:1.5'
                                          }
                                          v-html={(() => {
                                            return hightLight(
                                              props.row[i]
                                            );
                                          }
                                          )()}
                                        >

                                        </span>
                                        {(() => {
                                          if (subsidiary.value) {
                                            return (
                                              <span
                                                class='subsidiary select_helper_popup_single_row_table_subsidiary'
                                                style='display:block;font-size:12px;color;margin-top:4px;padding-left:4px;line-height:1.5'
                                                v-html={(() => {
                                                  const listProxy = props.row; //rows.value[i];
                                                  let str = subsidiary.value;
                                                  str = str
                                                    .replace(/(^["]|["]$)/g, '')
                                                    .replace(/(^[']|[']$)/g, '');
                                                  console.log(str); // 输出 "Hello, world!"

                                                  const subsidiaryText =
                                                    str?.indexOf('${') != -1
                                                      ? '`' + str + '`'
                                                      : str;

                                                  const getLabel = new Function(
                                                    `element`,
                                                    `with(element){
                                                      return ${subsidiaryText}
                                                  }`,
                                                  );

                                                  return hightLight(
                                                    getLabel(listProxy),
                                                  );
                                                })()}
                                              ></span>
                                            );
                                          }
                                        })()}
                                      </div>
                                     
                                    
                                   </div>
                                   {(()=>{
                                        if(!multiple.value){
                                          return <div style={'padding-right:8px;width:16px;height:16px;font-size:16px;height:100%;display:flex;align-items:center;justify-content:center'}>
                                          {(()=>{
                                            if(selectList.value.some(
                                              item =>
                                                item[valueField.value] == props.row[valueField.value],
                                            )){
                                              return <i class={'fas dx-icon icon-t-check-fine'} style={'color:var(--t-color)'}></i>
                                            }
                                          })()}
                                        </div>
                                        }
                                      })()}
                                 </div>
                                 {(() => {
                                   if (type.value == 'byPreview') {
                                     return (
                                       <div
                                       style={"flex:none"}
                                         onClick={() => {
                                           rows.value = rows.value.filter(
                                             item =>
                                               item[valueField.value] !=
                                               props.row[valueField.value],
                                           );
                                         }}
                                       >
                                         <t-button
                                            style='font-size:8px;margin-top:-4px'
                                            flat
                                            round
                                            dense
                                            icon='clear'
                                            onClick={e => {
                                              // rows.value = rows.value.filter(
                                              //   item =>
                                              //     item[valueField.value] !=
                                              //     props.row[valueField.value],
                                              // );
                                            }}
                                          />
                                         {/* {$q.lang.mixedView.button.delete} */}
                                       </div>
                                     );
                                   }
                                 })()}
                               </div>
                             </t-td>,
                           );
                        }

                      }
                      if (!rows.value || rows.value.length == 0) {
                        Template.push(<span>{$q.lang.table.noData}</span>)
                      }
                      return Template;
                    })()}
                  </t-tr>
                );
              },
            }}
          </t-table>
        </t-infinite-scroll>
      );

    };
    const renderLoading = () => {

      // if ((type.value != 'filter' &&rows.value.length == 0)||(type.value != 'filter'&&!filter.value&&!rows.value.length)) {
      //   return (
      //     <div style={'height:'+height.value}>
      //       <span style='    opacity: 0;'>1</span>
      //       <t-inner-loading
      //         showing={true}
      //         label='加载中...'
      //         label-class='text-teal'
      //         label-style='font-size: 1.1em'
      //       />
      //     </div>
      //   );
      // } else {
        return '';
      // }
    };
    return () => {
      return (
        <div  style={`    flex: 1;overflow: auto;${isMultiseriate.value?'padding:20px 20px 8px 20px ':''}`}>
           {(()=>{

            if(isMultiseriate.value){
             return <TInput class='searchByMultiseriate' modelValue={filter.value} onUpdate:modelValue={(e)=>{emit('update:filter',e)}}  style={'margin-bottom:8px;width:100%;max-width:1216px'} >
              {{
                prepend:()=>{
                    return <span style={`position:relative;font-size:12px;color: rgba(0, 0, 0, var(--t-color-opacity, /*批量处理90%透明度*/0.9));width:100%;display:flex;flex-wrap:wrap;align-items:center`}>
                      {
                        (()=>{
                          let Template=[]
                          if(dropPosition.value=='top'){
                          if(selectList.value.length>0){
                            selectList.value.forEach((element,index) => {
                              Template.push(
                                <span
                                class= 'select_helper_tag'
                                
                              >
                                <span class={'select-tag'} title={element[labelField.value]}>
                                {element[labelField.value]}
                                </span>
                                {(() => {
                                  if (index ==  selectList.value.length - 1) {
                                    return <i></i>;
                                  } else {
                                    return <i>,</i>;
                                  }
                                })()}
    
                                <t-button
                                  style={ 'font-size:8px;;'}
                                  flat
                                  round
                                  dense
                                  icon='clear'
                                  onClick={e => {
                                    selectList.value.splice(index, 1);
    
                                    if(e){
                                      e.stopPropagation()
                                      e.preventDefault()
                                      return false
                                    }
                                  }}
                                />
                              </span>
                               )
                            });
                          
                          }
                        }
                          Template.push(
                            <input
                              style='border:0;outline:0;height: 26px;line-height: 26px; width:100%;font-size:14px;;    flex: 1;min-width:10px;'
                
                              v-model={filter.value}
                              onInput={(e)=>{emit('update:filter',e.target.value)}}
                              class={'select_helper_input_inner q-placeholder'}
                              value={filter.value}
                              // modelValue={filter.value} onUpdate:modelValue={(e)=>{emit('update:filter',e)}}
                            />,
                          );
                          return Template
                        })()
                      }
                    </span>
                   
          
                }
              }}
             </TInput>
            }
          })()}
 <div
          style={
            (!($q.screen.xs||$q.platform.is.mobile)|| position.value == 'drop')&&!(columnarPattern.value&&multiple.value)
              ? `${isMultiseriate.value?'min-height:192px;':''}max-height:192px;min-height:64px; overflow-y: auto;width:${ width.value}px;}`
              : `height:100%;overflow-y: auto;width:${width.value}px`
          }
          ref={scrollTargetRef}
          class={!($q.screen.xs||$q.platform.is.mobile)?'':multiple.value?'isMutile':'isNotMutile'}
        >
          {renderLoading()}
         
          {renderInfinite()}
         
        </div>
        {(()=>{
            if(isMultiseriate.value){
             return <div style={'height:58px;display:flex;justify-content:center;align-items:center;gap:10px'}>  
              <t-button style='border:1px solid #DCDCDC;' onClick={()=>{
                emit('close') 
              }}>
              {/* 取消 */}
             {$q.lang.label.cancel} 
            </t-button>{' '}
            <t-button
              color='primary'
              onClick={() => {
                selection.value = selectList.value.map(item => item[valueField.value]);
                emit('updateSelectList', selectList.value);
                emit('close') 
              }}
            >
              {/* 确定 */}
              {$q.lang.label.ok} 
            </t-button>
             </div>
            }
          })()}
        </div>
       
      );
    };
  },
});
